#include  "head.h"
int main(int argc, char *argv[])
{
    // ./server 192.168.118.128 1234 3
    ARGS_CHECK(argc,4);
    int workernum = atoi(argv[3]);
    workerdata_t * workerdataArr = (workerdata_t *)calloc(workernum,sizeof(workerdata_t));
    makeWorker(workernum,workerdataArr);
    int sockfd;
    tcpInit(argv[1],argv[2],&sockfd);

    int epfd = epoll_create(1);
    epollAdd(epfd,sockfd);
    // 增加每个子进程的socket的监听
    for(int i = 0; i < workernum; ++i){
        epollAdd(epfd,workerdataArr[i].sockfd);
    }
    struct epoll_event readyset[1024];
    while(1){
        int readynum = epoll_wait(epfd,readyset,1024,-1);
        for(int i = 0; i < readynum; ++i){
            if(readyset[i].data.fd == sockfd){
                int netfd = accept(sockfd,NULL,NULL);
                printf("1 client is connected!\n");
                for(int j = 0;j < workernum; ++j){
                    if(workerdataArr[j].status == FREE){
                        sendfd(workerdataArr[j].sockfd,netfd);
                        workerdataArr[j].status = BUSY;
                        break;
                    }
                }
                close(netfd);
            }
            else {
                printf("1 worker finished his job!\n");
                for(int j = 0; j < workernum; ++j){
                    if(workerdataArr[j].sockfd == readyset[i].data.fd){
                        pid_t pid;
                        recv(workerdataArr[j].sockfd,&pid,sizeof(pid),0);
                        printf("No %d worker, pid = %d\n", j, pid);
                        workerdataArr[j].status = FREE;
                        break;
                    }
                }
            }
        }
    }
    return 0;

}

